<?php

namespace app\teacher\controller;

use app\admin\model\Admin;
use app\admin\model\classes\Teachers;
use app\common\library\AliSms;
use fast\Random;
use think\Cache;
use think\Db;

class Auth extends Base
{

    public $model = null;
    public function __construct(Admin $admin)
    {
        parent::__construct();
        $this->model = $admin;
    }

    /**
     * 登录
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login()
    {
        $username = $this->request->post('username', '');
        $password = $this->request->post('password', '');
        if (!$username) $this->error('账号不能为空');
        if (!$password) $this->error('密码不能为空');
        if (strlen($password) < 6) $this->error('密码不能少于六位');

        $user = Admin::where('username', $username)->where('status', 'normal')->find();
        if (!$user) $this->error('账号不存在');
        if ($user['password'] != md5(md5($password) . $user['salt'])) $this->error('密码错误');
        $teacher = Teachers::where('user_id', $user['id'])->find();
        if (!$teacher) $this->error('账号不存在！');
        $token = Random::uuid();
        Cache::set($token, $user['id']);
        $this->success('登录成功', ['token'=>$token]);
    }

    /**
     * 验证码登录，没有账号，但是有邀请人，注册并绑定邀请人学校，否则不允许登录
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function register()
    {
        $phone = $this->request->post('phone', '');
        if (!$phone) $this->error('请输入手机号');
        if (!is_phone($phone)) $this->error('请输入正确的手机号');

        $code = $this->request->post('code', '');
        if (!$code) $this->error('请输入验证码');
        $cacheCode = Cache::get('teacher_smsMsg'.$phone);
        if (!$cacheCode) $this->error('请发送短信验证码');
        if ($cacheCode != $code) $this->error('验证码错误');

        $user = Admin::where('mobile', $phone)->where('status', 'normal')->find();
        $pid = $this->request->post('pid', 0);
        if (!$user) {
            if (!$pid) $this->error('账号不存在');
            //创建教师及账号，并且绑定为邀请人的学校
            Db::startTrans();
            try {
                $nickname = '教师'.maskPhoneNumber($phone);
                //添加账号
                $udata['username'] = $phone;
                $udata['mobile'] = $phone;
                $udata['nickname'] = $nickname;
                $udata['salt'] = Random::alnum();
                $udata['password'] = md5(md5('123456') . $udata['salt']);
                $avatar = '/assets/img/avatar.png';
                $udata['createtime'] = time();
                $udata['avatar'] = $avatar;
                $udata['pid'] = $pid;
                $admin_id = Db::name('admin')->insertGetId($udata);
                $data = [
                    'uid' => $admin_id,
                    'group_id' => 3
                ];
                Db::name('auth_group_access')->insert($data);
                //添加教师记录
                $teacher = Teachers::where('user_id', $pid)->find();
                $tdata = [
                    'user_id' => $admin_id,
                    'realname' => $nickname,
                    'mobile' => $phone,
                    'gender' => 1,
                    'iscaptain' => 1,
                    'avatar' => $avatar,
                    'admin_id' => $teacher['admin_id'],
                    'createtime' => time(),
                ];
                Db::name('classes_teacher')->insert($tdata);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        } else {
            $teacher = Teachers::where('user_id', $user['id'])->find();
            if (!$teacher) $this->error('账号不存在！');
            $admin_id = $user['id'];
        }
        $token = Random::uuid();
        Cache::set($token, $admin_id);
        Cache::set('teacher_smsMsg'.$phone, '');
        $this->success('登录成功', ['token'=>$token]);
    }

    /**
     * 获取登录用户信息
     * @return array|bool|mixed|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function user()
    {
        return $this->model->where('id', $this->uid())->with('teacher')->find();
    }

    /**
     * 发送验证码
     * @return void
     */
    public function send_code()
    {
        $phone = $this->request->post('phone');
        $type = $this->request->post('type', 1); //1登录验证码 2重置密码
        if (!$phone) $this->error('请输入手机号');
        if (!is_phone($phone)) $this->error('请输入正确的手机号');

        if (Cache::get('teacher_smsMsg'.$phone)) $this->error('60s内不允许发送');
        $code = $this->makeCode();
        //$code = 1234;
        Cache::set('teacher_smsMsg'.$phone, $code, 60);
        $res = AliSms::main([
            'phone' => $phone,
            'code'  => $code
        ], $type);
        if ($res->body->code != 'OK') {
            $this->error('发送失败');
        }
        $this->success('发送成功');
    }

    public function reset_password()
    {
        $phone = $this->request->post('phone', '');
        if (!$phone) $this->error('请输入手机号');
        if (!is_phone($phone)) $this->error('请输入正确的手机号');

        $code = $this->request->post('code', '');
        if (!$code) $this->error('请输入验证码');
        $cacheCode = Cache::get('teacher_smsMsg'.$phone);
        if (!$cacheCode) $this->error('请发送短信验证码');
        if ($cacheCode != $code) $this->error('验证码错误');

        $user = Admin::where('mobile', $phone)->where('status', 'normal')->find();
        if (!$user) $this->error('账号不存在');

        $password = $this->request->post('password', '');
        $again_password = $this->request->post('again_password', '');
        if (!$password) $this->error('请输入密码');
        if (!$again_password) $this->error('请再次输入密码');

        if ($password != $again_password) $this->error('两次密码不一致');
        $user->salt = Random::alnum();
        $user->password = md5(md5($password).$user->salt);
        $res = $user->save();
        if ($res === false) $this->error('修改失败');
        Cache::set('teacher_smsMsg'.$phone, '');
        $this->success('修改成功');
    }

    public function makeCode()
    {
        return rand(1000,9999);
    }

    /**
     * 退出登录
     * @return void
     */
    public function login_out()
    {
        $token = $this->request->header('token');
        Cache::set($token, '');
        $this->success('退出成功');
    }


    public function up_user()
    {
        $username = $this->request->post('username', '');
        $avatar = $this->request->post('avatar', '');
        $is_get_notice = $this->request->post('is_get_notice', '');
        if (!$username && !$avatar && !$is_get_notice) $this->error('参数错误');

        $user = Admin::where('id', $this->uid())->find();
        if (!$user) $this->error('数据不存在');
        if ($username) $user->nickname = $username;
        if ($avatar) $user->avatar = $avatar;
        if ($is_get_notice) $user->is_get_notice = $is_get_notice;
        $res = $user->save();
        if ($res === false) $this->error('修改失败');
        $this->success('修改成功');
    }



}